
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Class-based views &#8212; Django 1.11.22.dev20190603194737 documentation</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Introduction to class-based views" href="intro.html" />
    <link rel="prev" title="Templates" href="../templates.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.11.22.dev20190603194737 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="../templates.html" title="Templates">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="intro.html" title="Introduction to class-based views">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-class-based-views-index">
            
  <div class="section" id="s-class-based-views">
<span id="class-based-views"></span><h1>Class-based views<a class="headerlink" href="#class-based-views" title="Permalink to this headline">¶</a></h1>
<p>A view is a callable which takes a request and returns a
response. This can be more than just a function, and Django provides
an example of some classes which can be used as views. These allow you
to structure your views and reuse code by harnessing inheritance and
mixins. There are also some generic views for simple tasks which we’ll
get to later, but you may want to design your own structure of
reusable views which suits your use case. For full details, see the
<a class="reference internal" href="../../ref/class-based-views/index.html"><span class="doc">class-based views reference documentation</span></a>.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="intro.html">Introduction to class-based views</a></li>
<li class="toctree-l1"><a class="reference internal" href="generic-display.html">Built-in class-based generic views</a></li>
<li class="toctree-l1"><a class="reference internal" href="generic-editing.html">Form handling with class-based views</a></li>
<li class="toctree-l1"><a class="reference internal" href="mixins.html">Using mixins with class-based views</a></li>
</ul>
</div>
<div class="section" id="s-basic-examples">
<span id="basic-examples"></span><h2>Basic examples<a class="headerlink" href="#basic-examples" title="Permalink to this headline">¶</a></h2>
<p>Django provides base view classes which will suit a wide range of applications.
All views inherit from the <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View" title="django.views.generic.base.View"><code class="xref py py-class docutils literal notranslate"><span class="pre">View</span></code></a> class, which
handles linking the view in to the URLs, HTTP method dispatching and other
simple features. <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.RedirectView" title="django.views.generic.base.RedirectView"><code class="xref py py-class docutils literal notranslate"><span class="pre">RedirectView</span></code></a> is for a
simple HTTP redirect, and <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.TemplateView" title="django.views.generic.base.TemplateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateView</span></code></a>
extends the base class to make it also render a template.</p>
</div>
<div class="section" id="s-simple-usage-in-your-urlconf">
<span id="simple-usage-in-your-urlconf"></span><h2>Simple usage in your URLconf<a class="headerlink" href="#simple-usage-in-your-urlconf" title="Permalink to this headline">¶</a></h2>
<p>The simplest way to use generic views is to create them directly in your
URLconf. If you’re only changing a few simple attributes on a class-based view,
you can simply pass them into the
<a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View.as_view" title="django.views.generic.base.View.as_view"><code class="xref py py-meth docutils literal notranslate"><span class="pre">as_view()</span></code></a> method call itself:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="k">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="k">import</span> <span class="n">TemplateView</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^about/$&#39;</span><span class="p">,</span> <span class="n">TemplateView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(</span><span class="n">template_name</span><span class="o">=</span><span class="s2">&quot;about.html&quot;</span><span class="p">)),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>Any arguments passed to <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View.as_view" title="django.views.generic.base.View.as_view"><code class="xref py py-meth docutils literal notranslate"><span class="pre">as_view()</span></code></a> will
override attributes set on the class. In this example, we set <code class="docutils literal notranslate"><span class="pre">template_name</span></code>
on the <code class="docutils literal notranslate"><span class="pre">TemplateView</span></code>. A similar overriding pattern can be used for the
<code class="docutils literal notranslate"><span class="pre">url</span></code> attribute on <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.RedirectView" title="django.views.generic.base.RedirectView"><code class="xref py py-class docutils literal notranslate"><span class="pre">RedirectView</span></code></a>.</p>
</div>
<div class="section" id="s-subclassing-generic-views">
<span id="subclassing-generic-views"></span><h2>Subclassing generic views<a class="headerlink" href="#subclassing-generic-views" title="Permalink to this headline">¶</a></h2>
<p>The second, more powerful way to use generic views is to inherit from an
existing view and override attributes (such as the <code class="docutils literal notranslate"><span class="pre">template_name</span></code>) or
methods (such as <code class="docutils literal notranslate"><span class="pre">get_context_data</span></code>) in your subclass to provide new values
or methods. Consider, for example, a view that just displays one template,
<code class="docutils literal notranslate"><span class="pre">about.html</span></code>. Django has a generic view to do this -
<a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.TemplateView" title="django.views.generic.base.TemplateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateView</span></code></a> - so we can just subclass it,
and override the template name:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># some_app/views.py</span>
<span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="k">import</span> <span class="n">TemplateView</span>

<span class="k">class</span> <span class="nc">AboutView</span><span class="p">(</span><span class="n">TemplateView</span><span class="p">):</span>
    <span class="n">template_name</span> <span class="o">=</span> <span class="s2">&quot;about.html&quot;</span>
</pre></div>
</div>
<p>Then we just need to add this new view into our URLconf.
<a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.TemplateView" title="django.views.generic.base.TemplateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateView</span></code></a> is a class, not a function,
so we point the URL to the <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View.as_view" title="django.views.generic.base.View.as_view"><code class="xref py py-meth docutils literal notranslate"><span class="pre">as_view()</span></code></a>
class method instead, which provides a function-like entry to class-based
views:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># urls.py</span>
<span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="k">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">some_app.views</span> <span class="k">import</span> <span class="n">AboutView</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^about/$&#39;</span><span class="p">,</span> <span class="n">AboutView</span><span class="o">.</span><span class="n">as_view</span><span class="p">()),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>For more information on how to use the built in generic views, consult the next
topic on <a class="reference internal" href="generic-display.html"><span class="doc">generic class-based views</span></a>.</p>
<div class="section" id="s-supporting-other-http-methods">
<span id="s-id1"></span><span id="supporting-other-http-methods"></span><span id="id1"></span><h3>Supporting other HTTP methods<a class="headerlink" href="#supporting-other-http-methods" title="Permalink to this headline">¶</a></h3>
<p>Suppose somebody wants to access our book library over HTTP using the views
as an API. The API client would connect every now and then and download book
data for the books published since last visit. But if no new books appeared
since then, it is a waste of CPU time and bandwidth to fetch the books from the
database, render a full response and send it to the client. It might be
preferable to ask the API when the most recent book was published.</p>
<p>We map the URL to book list view in the URLconf:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="k">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">books.views</span> <span class="k">import</span> <span class="n">BookListView</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^books/$&#39;</span><span class="p">,</span> <span class="n">BookListView</span><span class="o">.</span><span class="n">as_view</span><span class="p">()),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>And the view:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.http</span> <span class="k">import</span> <span class="n">HttpResponse</span>
<span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="k">import</span> <span class="n">ListView</span>
<span class="kn">from</span> <span class="nn">books.models</span> <span class="k">import</span> <span class="n">Book</span>

<span class="k">class</span> <span class="nc">BookListView</span><span class="p">(</span><span class="n">ListView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Book</span>

    <span class="k">def</span> <span class="nf">head</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">last_book</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_queryset</span><span class="p">()</span><span class="o">.</span><span class="n">latest</span><span class="p">(</span><span class="s1">&#39;publication_date&#39;</span><span class="p">)</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
        <span class="c1"># RFC 1123 date format</span>
        <span class="n">response</span><span class="p">[</span><span class="s1">&#39;Last-Modified&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">last_book</span><span class="o">.</span><span class="n">publication_date</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%a</span><span class="s1">, </span><span class="si">%d</span><span class="s1"> %b %Y %H:%M:%S GMT&#39;</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">response</span>
</pre></div>
</div>
<p>If the view is accessed from a <code class="docutils literal notranslate"><span class="pre">GET</span></code> request, a plain-and-simple object
list is returned in the response (using <code class="docutils literal notranslate"><span class="pre">book_list.html</span></code> template). But if
the client issues a <code class="docutils literal notranslate"><span class="pre">HEAD</span></code> request, the response has an empty body and
the <code class="docutils literal notranslate"><span class="pre">Last-Modified</span></code> header indicates when the most recent book was published.
Based on this information, the client may or may not download the full object
list.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Class-based views</a><ul>
<li><a class="reference internal" href="#basic-examples">Basic examples</a></li>
<li><a class="reference internal" href="#simple-usage-in-your-urlconf">Simple usage in your URLconf</a></li>
<li><a class="reference internal" href="#subclassing-generic-views">Subclassing generic views</a><ul>
<li><a class="reference internal" href="#supporting-other-http-methods">Supporting other HTTP methods</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="../templates.html"
                        title="previous chapter">Templates</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="intro.html"
                        title="next chapter">Introduction to class-based views</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/topics/class-based-views/index.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Jun 03, 2019</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="../templates.html" title="Templates">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="intro.html" title="Introduction to class-based views">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>